package Chapter6.WebTable;

import org.openqa.selenium.*;
import org.openqa.selenium.Point;
import org.openqa.selenium.internal.WrapsDriver;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * Created by m.zabarylo on 10/3/2014.
 */
public class WebElementExtender {
    public static void setAttribute(WebElement element, String attributeName, String value)
    {
        WrapsDriver wrappedElement = (WrapsDriver) element;

        JavascriptExecutor driver = (JavascriptExecutor) wrappedElement.getWrappedDriver();
        driver.executeScript("arguments[0].setAttribute(arguments[1],arguments[2])", element, attributeName, value);
    }

    public static void hightlightElement(WebElement element)
    {
        for (int i = 0; i < 5; i++){
            WrapsDriver wrappedElement = (WrapsDriver) element;
            JavascriptExecutor driver = (JavascriptExecutor) wrappedElement.getWrappedDriver();
            driver.executeScript("arguments[0].setAttribute('style', arguments[1]);",
                    element, "color: green; border: 2px solid green;");
            driver.executeScript("arguments[0].setAttribute('style', arguments[1]);",
                    element, "");
        }
    }

    public static File captureElementBitmap(WebElement element) throws Exception
    {
        //get the wrapsdriver of webelement
        WrapsDriver wrapsDriver = (WrapsDriver) element;

        //get the entire screenshot from the driver of passed  WebElement
        File screen = ((TakesScreenshot) wrapsDriver.getWrappedDriver()).getScreenshotAs(OutputType.FILE);

        //create an instance of Buffered Image from captured screenshot
        BufferedImage img = ImageIO.read(screen);

        //get the width and height of the WebElement using getSize()
        int width = element.getSize().getWidth();
        int height = element.getSize().getHeight();
        //create a rectangle using width and height
        Rectangle rect = new Rectangle(width,height);
        //get the location of webelement in a Point
        //this will provide X & Y coordinates of the WebElement
        Point p = element.getLocation();

        //create image by for element using its location and size
        //this will give image data specific to the WebElement
        BufferedImage dest = img.getSubimage(p.getX(), p.getY(), rect.width, rect.height);

        //write back the image data for element in File object
        ImageIO.write(dest, "png", screen);

        return screen;
    }
}
